package com.jyg.common.exception;


import com.jyg.common.result.Result;
import com.jyg.common.result.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ControllerAdvice
@Slf4j
public class CustomExceptionHandler {

    /**
     * 自定义异常（业务异常）
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public Result<?> returnMyException(CustomException e) {
        Result<?> result = e.getResult();
        log.error(result.getMsg(), e);
        return result;
    }

    /**
     * 参数校验
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<?> returnException(MethodArgumentNotValidException e) {
        log.error(ResultEnum.FORM.getMsg(), e);
        BindingResult result = e.getBindingResult();
        return new Result<>(ResultEnum.FORM, result.getAllErrors().get(0).getDefaultMessage());
    }

    /**
     * 处理前端表单格式异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = org.springframework.http.converter.HttpMessageNotReadableException.class)
    @ResponseBody
    public Result<?> handlingFrontEndFormFormatExceptions(org.springframework.http.converter.HttpMessageNotReadableException e) {
        log.error(ResultEnum.FORM.getMsg(), e);
        return new Result<>(ResultEnum.FORM);
    }

    /**
     * 处理空指针的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result<?> exceptionHandler(NullPointerException e) {
        log.error(ResultEnum.NULL_POINTER.getMsg(), e);
        return new Result<>(ResultEnum.NULL_POINTER);
    }

    /**
     * 其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<?> exceptionHandler(Exception e) {
        log.error(ResultEnum.FAILED.getMsg(), e);
        return new Result<>(ResultEnum.FAILED);
    }

    public Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError error : errorList) {
            // 发送验证错误的时候所对应的某个属性
            String field = error.getField();
            // 验证的错误消息
            String msg = error.getDefaultMessage();
            map.put(field, msg);
        }
        return map;
    }
}
